<script setup lang="ts">
  import routeComponentName from '@/config/route-component-name'
  import { v4 as uuidv4 } from 'uuid'
  import { initWebSocket } from '@/utils/socket'
  import { dataBackup } from '@/api/system'
  import useBackupService from './useBackupService'
  import { HMessageBox } from '@/components/common/message'

  const { isBackuping, setBackupStatusToEnd, setBackupStatusToStart } = useBackupService()

  defineOptions({
    name: routeComponentName.setting.backups,
  })

  /**
   * 开始备份点击事件
   */
  const onStartBackupClick = () => {
    const uuid = uuidv4()
    initWebSocket(
      async (msg) => {
        if (msg && msg.code && msg.code === 20000) {
          const res = await dataBackup(uuid)
          if (res.data.code === 20000) {
            setBackupStatusToStart()
          }
        }

        if (msg && msg.code && msg.code !== 20000) {
          HMessageBox.error(msg.message)
          setBackupStatusToEnd()
        }

        if (msg && Object.hasOwn(msg, 'code') && msg.code === 0) {
          HMessageBox.success(msg.message)
          setBackupStatusToEnd()
        }
      },
      `/ws/backup/${uuid}`,
      () => {
        setBackupStatusToEnd()
      },
    )
  }
</script>

<template>
  <div class="data-backups">
    <div class="container">
      <div class="sql-backups">
        <div class="text">
          <div class="title"> 数据备份 </div>
          <div class="desc"> 包含：工单、条码、客户、网点、仓库、产品、权限、收款 </div>
        </div>
        <h-button type="primary" :loading="isBackuping" @click="onStartBackupClick">{{
          isBackuping ? '备份中' : '开始备份'
        }}</h-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .data-backups {
    width: 100%;
    height: calc(100vh - 92px);
    padding: 12px;
    box-sizing: border-box;

    .container {
      background-color: #fff;
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      padding: 12px;
      display: flex;
      flex-direction: column;
      row-gap: 24px;

      .sql-backups,
      .img-backups,
      .video-backups {
        box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.1);
        width: 100%;
        height: fit-content;
        padding: 12px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        column-gap: 24px;
        border-radius: 4px;

        .text {
          display: flex;
          flex-direction: column;
          row-gap: 4px;

          .title {
            font-size: 16px;
            font-weight: bold;
          }

          .desc {
            color: gray;
          }
        }
      }
    }
  }

  .loading {
    background-color: #fff;
    opacity: 0.5;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
  }
</style>
